package com.xinzhitong.www.controller;

import com.xinzhitong.www.enumeration.CollectionType;
import com.xinzhitong.www.exception.collection.CollectionEmptyException;
import com.xinzhitong.www.exception.collection.CollectionExistException;
import com.xinzhitong.www.exception.collection.CollectionNotExistException;
import com.xinzhitong.www.service.CollectionService;
import com.xinzhitong.www.utils.Message;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 收藏控制器
 *
 * @author 徐鑫
 */
@CrossOrigin
@RestController
@RequestMapping("collect")
public class CollectionController {

    @Resource
    CollectionService collectionService;

    /**
     * 分页获取用户的收藏
     *
     * @param collectionType 收藏类型
     * @param pageNo         页码
     * @param pageSize       页大小
     * @return 收藏信息列表
     */
    @RequestMapping(value = "collections", method = RequestMethod.GET)
    public Message collections(
            @RequestParam("collectionType") CollectionType collectionType,
            @RequestParam("pageNo") Integer pageNo,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize
    ) {
        String msg;
        try {
            return Message.createSuc(collectionService.getCollections(collectionType, pageNo, pageSize));
        } catch (CollectionEmptyException e) {
            e.printStackTrace();
            msg = "收藏为空";
        }
        return Message.createErr(msg);
    }

    /**
     * 收藏一个物品
     *
     * @param collectionId   收藏物id
     * @param collectionType 收藏类型
     * @return 响应信息
     */
    @RequestMapping(value = "aCollection", method = RequestMethod.PUT)
    public Message aCollection(
            @RequestParam("collectionId") Integer collectionId,
            @RequestParam("collectionType") CollectionType collectionType
    ) {
        String msg = "收藏成功！";
        try {
            collectionService.addACollection(collectionId, collectionType);
            return Message.createSuc(msg);
        } catch (CollectionExistException e) {
            e.printStackTrace();
            msg = "已收藏该" + e.getMessage();
        } catch (CollectionNotExistException e) {
            e.printStackTrace();
            msg = "收藏目标已失效";
        }
        return Message.createErr(msg);
    }

    /**
     * 批量移除收藏
     *
     * @param collectionId   收藏物id
     * @param collectionType 收藏类型
     * @return 响应信息
     */
    @RequestMapping(value = "theCollections", method = RequestMethod.DELETE)
    public Message theCollections(
            @RequestParam("collectionId") Integer[] collectionId,
            @RequestParam("collectionType") CollectionType[] collectionType
    ) {
        String msg = "移除成功";
        collectionService.removeTheCollectionOf(collectionId, collectionType);
        return Message.createSuc(msg);
    }

}
